import tkinter as tk
# 随机数
import random

# 初始化变量
running = False
timer = None
sum = 0
char = 'function(){}*0123456789 ;='
a1 = 1
a2 = 2
r1 = 2
r2 = 4

# 实验开关
def is_run():
    global running,timer,a1,a2,r1,r2
    if running:
        button.config(text='开始实验')
        running = False
        root.after_cancel(timer)
    else:
        button.config(text='停止实验')
        # 修改初始化的变量
        running = True
        a1 = a1_box.get()
        a2 = a2_box.get()
        r1 = r1_box.get()
        r2 = r2_box.get()
        print(a1,a2,r1,r2)
        fun()

# 函数生成与验证
def fun():
    global sum,timer
    f = code_box.get("1.0", "end-1c")
    try:
        # 替代函数
        js = 'f = ' + f
        exec(js)
        # 模型验证
        if f(a1) == r1 and f(a2) == r2:
            # 找到模型
            result_label.config(text=f)
            # 停止测试
            is_run()
        else:
            raise Exception("模型验证失败")
    except Exception as e:
        # 随机字符串总长度
        len = 10 + random.randint(0, 90)
        f = ''.join(random.choice(char) for i in range(len))
        # 显代码
        code_box.delete("1.0", "end")
        code_box.insert("1.0", f)
        # 显示失败次数
        sum += 1
        result_label.config(text='失败第 ' + str(sum) + ' 次')
        # 定时任务，1秒钟尝试一次，此处也可以根据需要调整频率
        timer = root.after(1000, fun)


# 创建窗口
root = tk.Tk()
root.title("运行JS代码")
root.geometry("500x300")


# 创建文本框
code_box = tk.Text(root, width=50, height=5)
code_box.pack(fill="x")
# 创建结果标签
result_label = tk.Label(root, text='')
result_label.pack(fill="x")

# 创建参数文本框
tk.Label(root, text="目标").pack(side='left')
a1_box = tk.Entry(root, width=5)
a1_box.insert(0,a1)
a1_box.pack(side='left')
tk.Label(root, text="=").pack(side='left')
r1_box = tk.Entry(root, width=5)
r1_box.insert(0,r1)
r1_box.pack(side='left')
tk.Label(root, text="并且").pack(side='left')
a2_box = tk.Entry(root, width=5)
a2_box.insert(0,a2)
a2_box.pack(side='left')
tk.Label(root, text="=").pack(side='left')
r2_box = tk.Entry(root, width=5)
r2_box.insert(0,r2)
r2_box.pack(side='left')
# 创建按钮
button = tk.Button(root, text='开始实验', command=is_run)
button.pack(side='left')

# 运行主循环
root.mainloop()